import {RouterMount,createRouter} from 'uni-simple-router';
import store from "../store/store.js"
import axios from 'axios'
import {baseURL} from "../util/axiosPlugin.js";
// import {popup} from "../component/popup.js"
const router = createRouter({
	mode:"history",
	platform: process.env.VUE_APP_PLATFORM,
	routes: [...ROUTES]
	});
const constantRoutes=[
	"/pages/login/login",
	"/pages/login/register",
	"/pages/login/forgetPassword",
	"/pages/login/chooseCountry",
	"/pages/login/forgetPasswordVerification",
	"/pages/login/forgetPasswordCodeVerfication",
	"/pages/login/loginByPhoneCode",
	
]
//全局路由前置守卫
router.beforeEach((to, from, next) => {
	console.log("topath",to)
	let constantRouterFlag=false
	
	for(let i in constantRoutes){
		if (constantRoutes[i]==to.path){
			constantRouterFlag=true
			break
		}
	}
	
	if(!constantRouterFlag){
		checkPermission(to).then(hasPermission=>{
			if(hasPermission){
				console.log("this.getApp()",getApp())
				next()
			}else{
				console.log("this.getApp()",getApp())
				uni.showToast({
					title:"对不起，您没有访问权限",
					icon:"none",
					duration:2000
				})
			}
		})

	}else{
		next()
	}
	
});
// 全局路由后置守卫
router.afterEach((to, from) => {

})
async function checkPermission(to){
	let roles
	if(store.state.userInfo==null){
		 await getUserInfo()
	}
	
	roles=store.state.userInfo.roles

	
	return hasPermission(roles,to)

}
function hasPermission(roles, route) {

  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}
//向服务器请求用户基本信息并建立会话缓存
async function getUserInfo(callback= function(){}) {
	// console.log("getUserInfo")
    //向服务器请求用户基本信息
    await axios({
        method: 'get',
        url: baseURL+'/user/get',
        headers:{
            Authorization:uni.getStorageSync("token"),
        }
    }).then((response) => {
        //token未失效时
        let responseData = response.data;
         //获取用户基本信息并存入sessionStorage（单次会话级存储）
		store.state.userInfo=responseData.msg
		console.log("userInfo",store.state.userInfo)
		getPark();
        //生成动态权限路由表
        // router.addRoutes(routerMatch(responseData.msg.role));
        //执行回调
        callback();
    }).catch((error)=>{
        console.log(error)
        //返回登录页
        uni.removeStorageSync('token');
        store.state.userInfo=null
        router.push({
			path:'/pages/login/login'
			});
        //执行回调
        callback();
    })
}
function getPark(){
	// console.log("getPark",store.state.userInfo.parkId)
	if(store.state.userInfo.parkId==''){
		axios({
			method:"get",
			url:baseURL+"/park/all",
			headers:{
				Authorization:uni.getStorageSync("token")
			}
		}).then((response)=>{
			let responseData=response.data
			// console.log(responseData)
			store.state.currentPark=response.data.msg[0];
		});
	}else{
		axios({
			method:"get",
			url:baseURL+"/park/get",
			headers:{
				Authorization:uni.getStorageSync("token")
			},
			params:{
				park_id:store.state.userInfo.parkId
			}
		}).then((response)=>{
			store.state.currentPark=response.data.msg
		});
	}

}
export {
	router,
	RouterMount
}